import db from '../db/index.js'
import bcrypt from 'bcryptjs'
import jwt from 'jsonwebtoken'
import config from '../config.js'

// 用户注册
export async function registerUser(req, res) {
  const userInfo = req.body;

  userInfo.password = bcrypt.hashSync(userInfo.password, 10);

  try {
    const [rows] = await db.query('SELECT * FROM user WHERE username = ?', [userInfo.username]);

    if (rows.length > 0) {
      res.status(400).json({
        status: 400,
        message: '用户名已被占用',
      });
    } else {
      await db.query('INSERT INTO user (username, password) VALUES (?, ?)', [userInfo.username, userInfo.password]);

      res.status(200).json({
        status: 200,
        message: '注册成功',
      });
    }
  } catch (err) {
    console.log('Error querying database:', err);

    res.status(500).json({
      status: 500,
      message: '服务异常',
    });
  }
}


//用户登录
export async function loginUser(req, res) {
  const { username, password } = req.body;
  try {
    const [rows] = await db.query('SELECT * FROM user WHERE username = ?', [username]);
    if (rows.length > 0) {
      const  isPasswordValid = bcrypt.compareSync(password,rows[0].password)//验证密码
      if(isPasswordValid){
        const user = {...rows[0], password: '',user_pic:''}
        const tokenStr =  jwt.sign( user, config.secretKey,{ expiresIn :config.expiresIn} ); // 生成token
      res.status(200).json({
        status: 200,
        message: '登录成功',
        token: 'Bearer ' + tokenStr, // 将token添加到响应中
      })
      }else {
        res.status(401).json({
          status: 401,
          message: '用户名或密码错误',
        });
      }
    } else {
      res.status(401).json({
        status: 401,
        message: '用户名或密码错误',
      });
    }
  } catch (err) {
    console.log('Error querying database:', err);
    res.status(500).json({
      status: 500,
      message: '服务异常',
    });
  }
}
